package com.sduept.nwld.dataserver.controller.daily;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.codec.binary.Base64;
import org.jsoup.Connection.Method;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.ParamManager;
import com.sduept.core.entity.SystemParameter;
import com.sduept.generator.ObjectId;
import com.sduept.utils.DateUtil;
import com.sduept.utils.WebRequestUtil;

/**
 * E文件下载Controller
 * 
 * @author RY
 *
 */
@ViewScoped
@Named
public class ViewEFilesController extends AbstractController {
	private static final long serialVersionUID = 5341953428253912650L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private ParamManager pc;
	
	private List<EFileDto> fileDtos = new ArrayList<ViewEFilesController.EFileDto>();
	private Date startTime;
	private Date endTime;
	private StreamedContent file;

	@PostConstruct
	public void init() {
		initSearchTime();
		getFileList();
		search();
	}

	/**
	 * 初始化时间。默认查看昨天和今天的E文件
	 */
	private void initSearchTime() {
		endTime = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(endTime);
		c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
		startTime = c.getTime();
	}

	public void resetQuery(){
		initSearchTime();
		getFileList();
		search();
	}
	
	public void search() {
		getFileList();
	}

	public static Date formatterDate(String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			date = new Date();
		}
		return date;
	}
	
	@SuppressWarnings("unchecked")
	private void getFileList() {
		fileDtos.clear();
		SystemParameter osbIpSp = pc.get(ParamDesc.OSB_IP);
		Map<String, String> requestParams = new HashMap<>();
		requestParams.put("start", DateUtil.getStringDate(startTime, DateUtil.pattern_ymdhms));
		requestParams.put("end", DateUtil.getStringDate(endTime, DateUtil.pattern_ymdhms));
		Pattern p = Pattern.compile("pas_e_(\\d+).txt.gz");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		List<String> fileNames = null;
		try {
			String jsonStr = WebRequestUtil.getRequest(
					"http://" + osbIpSp.getValue()
							+ "/rest/EfileQueryService/eFiles", Method.GET,
					requestParams);
			fileNames = (List<String>) JSONObject.parse(jsonStr);
			for (String fileName : fileNames) {
				Matcher m = p.matcher(fileName);
				if (!m.matches()){
					break;
				}

				String dateStr = m.group(1);
				try {
					Date fileDate = sdf.parse(dateStr);
					EFileDto dto = new EFileDto(ObjectId.get().toString(),fileName, fileDate);
					fileDtos.add(dto);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			addErrorMessage("获取文件列表失败！");
		}
		sortFileList();
	}

	private void sortFileList() {
		Collections.sort(fileDtos, new Comparator<EFileDto>() {
			@Override
			public int compare(EFileDto o1, EFileDto o2) {
				return o2.getTime().compareTo(o1.getTime());
			}
		});
	}

	public void downLoad(final EFileDto fileDto) {
		SystemParameter osbIpSp = pc.get(ParamDesc.OSB_IP);
		Map<String, String> requestParams = new HashMap<>();
		requestParams.put("fileName", fileDto.getFileName());
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			String jsonStr = WebRequestUtil.getRequest(
					"http://" + osbIpSp.getValue()
							+ "/rest/EfileQueryService/downEfile", Method.GET,
					requestParams);
			Base64 base64 = new Base64();
			byte[] bytes = base64.decode(jsonStr);
			final File f = new File(pros.getExportTempPath() + fileDto.getFileName());
			f.createNewFile();
			fos = new FileOutputStream(f);
			fos.write(bytes);
			fos.flush();

			fis = new FileInputStream(f);
			file = new DefaultStreamedContent(fis, "gz", fileDto.getFileName());
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(30000); // 等待文件下载完成后删除
						File f = new File(pros.getExportTempPath()
								+ fileDto.getFileName());
						f.delete();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("文件下载失败");
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public Date getStartTime() {
		return startTime;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	public class EFileDto implements Serializable{
		private static final long serialVersionUID = 1425372065101896781L;
		private String id;
		private String fileName;
		private Date time;

		public EFileDto(String id, String fileName, Date time) {
			super();
			this.id = id;
			this.fileName = fileName;
			this.time = time;
		}

		public String getId() {
			return id;
		}

		public String getFileName() {
			return fileName;
		}

		public Date getTime() {
			return time;
		}

		public void setId(String id) {
			this.id = id;
		}

		public void setFileName(String fileName) {
			this.fileName = fileName;
		}

		public void setTime(Date time) {
			this.time = time;
		}
	}

	public List<EFileDto> getFileDtos() {
		return fileDtos;
	}

	public void setFileDtos(List<EFileDto> fileDtos) {
		this.fileDtos = fileDtos;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}
}
